import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router'
import { mockRequest } from '@/api/mock'
import config from '@/config'
import { logger } from '@/utils/logger'

// 是否启用mock
const enableMock = config.api.enableMock

// 创建axios实例
const service = axios.create({
  baseURL: config.api.baseUrl,
  timeout: config.api.timeout,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 记录请求日志
    logger.logApiRequest(config.method.toUpperCase(), config.url, config.method === 'get' ? config.params : config.data)
    
    // 从localStorage获取token
    if (config.api.withToken) {
      const token = localStorage.getItem(config.storage.tokenKey)
      if (token) {
        config.headers['Authorization'] = `Bearer ${token}`
      }
    }
    return config
  },
  error => {
    logger.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    
    // 记录响应日志
    logger.logApiResponse(response.config.method.toUpperCase(), response.config.url, res)

    // 根据后端约定的状态码判断请求是否成功
    if (res.code !== 200) {
      // 处理各种错误情况
      if (res.code === 401) {
        // 未授权，清除token并重定向到登录页
        ElMessageBox.confirm('登录状态已过期，请重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          localStorage.removeItem(config.storage.tokenKey)
          localStorage.removeItem(config.storage.userInfoKey)
          localStorage.removeItem(config.storage.roleKey)
          router.push(config.router.login)
        })
      } else if (res.code === 403) {
        // 权限不足
        ElMessage({
          message: res.message || '权限不足',
          type: 'error',
          duration: 5 * 1000
        })
      } else {
        // 其他错误
        ElMessage({
          message: res.message || '请求失败',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(new Error(res.message || '请求失败'))
    } else {
      return res
    }
  },
  error => {
    // 记录错误日志
    logger.logApiError(
      error.config?.method?.toUpperCase() || 'UNKNOWN',
      error.config?.url || 'UNKNOWN',
      error
    )
    
    // 处理网络错误或服务器错误
    const { response } = error
    let message = '网络错误，请稍后再试'
    
    if (response) {
      switch (response.status) {
        case 400:
          message = '请求错误'
          break
        case 401:
          message = '未授权，请重新登录'
          // 清除token并跳转到登录页
          localStorage.removeItem(config.storage.tokenKey)
          localStorage.removeItem(config.storage.userInfoKey)
          localStorage.removeItem(config.storage.roleKey)
          router.push(config.router.login)
          break
        case 403:
          message = '拒绝访问'
          break
        case 404:
          message = '请求地址出错'
          break
        case 408:
          message = '请求超时'
          break
        case 500:
          message = '服务器内部错误'
          break
        case 501:
          message = '服务未实现'
          break
        case 502:
          message = '网关错误'
          break
        case 503:
          message = '服务不可用'
          break
        case 504:
          message = '网关超时'
          break
        default:
          message = `未知错误(${response.status})`
      }
    }
    
    ElMessage({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    
    return Promise.reject(error)
  }
)

// 封装请求函数
const request = function(config) {
  if (enableMock) {
    return mockRequest(config.url, config.method === 'get' ? config.params : config.data, config.method.toUpperCase())
  }
  return service(config)
}

// 添加便捷方法
request.get = function(url, params, config = {}) {
  if (enableMock) {
    return mockRequest(url, params, 'GET')
  }
  return service.get(url, { params, ...config })
}

request.post = function(url, data, config = {}) {
  if (enableMock) {
    return mockRequest(url, data, 'POST')
  }
  return service.post(url, data, config)
}

request.put = function(url, data, config = {}) {
  if (enableMock) {
    return mockRequest(url, data, 'PUT')
  }
  return service.put(url, data, config)
}

request.delete = function(url, params, config = {}) {
  if (enableMock) {
    return mockRequest(url, params, 'DELETE')
  }
  return service.delete(url, { params, ...config })
}

request.upload = function(url, file, onUploadProgress = null) {
  if (enableMock) {
    return mockRequest(url, { file: file.name }, 'POST')
  }
  
  const formData = new FormData()
  formData.append('file', file)
  
  return service.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress
  })
}

request.download = function(url, params, filename) {
  if (enableMock) {
    ElMessage({
      message: '模拟模式下不支持文件下载',
      type: 'warning'
    })
    return Promise.resolve()
  }
  
  return service.get(url, { 
    params, 
    responseType: 'blob' 
  }).then(response => {
    // 创建blob链接并下载
    const blob = new Blob([response.data])
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = filename
    link.click()
    URL.revokeObjectURL(link.href)
  })
}

export default request 